package com.iretailer.report.quartz;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.iretailer.report.influxdb.dao.InfluxdbBaseDao;
import com.iretailer.report.model.Categories;
import com.iretailer.report.model.Device;
import com.iretailer.report.service.CategoriesService;
import com.iretailer.report.service.DevicesService;
import com.iretailer.report.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.influxdb.dto.Point;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @Program: report
 * @Description:
 * @Author: Bennie
 * @Date: 2021-02-04 15:07
 **/
@Slf4j
@Component("easAlarmCollect")
public class EasAlarmCollect {

    @Value("${influxdb.dbName}")
    private String dbName;
    @Value("${influxdb.url}")
    private String url;

    @Autowired
    private InfluxdbBaseDao influxdbBaseDao;
    @Autowired
    private DevicesService devicesService;
    @Autowired
    private CategoriesService categoriesService;

    public void execute() {
        log.info("------------------开始同步EAS设备报警记录------------------");
        Categories eas = categoriesService.selectCategoryByKeyName("Eas");
        List<Device> deviceList = devicesService.list(new QueryWrapper<Device>().lambda()
                .eq(Device::getDeviceType, eas.getId())
                .eq(Device::getEnabled, 1)
                .isNotNull(Device::getWebUrl));
        deviceList.forEach(d -> {
            if (StringUtil.notEmpty(d.getWebUrl())) {
                log.info("同步EAS设备报警记录: DeviceId:{}, DeviceName:{}", d.getDeviceId(), d.getDeviceName());
                String webUrl = d.getWebUrl();
                while (webUrl.endsWith("/")) {
                    webUrl = webUrl.substring(0, webUrl.length() - 1);
                }
                String apiUrl = webUrl + "/api/v1/getAlertLog?count=500";
                try {
                    String response = HttpUtil.get(apiUrl);
                    JSONArray jsonArray = JSONUtil.parseArray(response);
                    List<Point> insertList = new ArrayList<>();
                    for (int i = 0; i < jsonArray.size(); i++) {
                        JSONObject object = jsonArray.getJSONObject(i);
                        if (object != null && StringUtil.notEmpty(object.getStr("EPC"))) {
                            insertList.add(buildPoint(object.getLong("AlertTime"),
                                    d.getId().toString(), object.getStr("EPC"),
                                    object.getInt("Rssi"), object.getInt("RuleNum")));
                        }
                    }
                    if (!insertList.isEmpty()) {
                        influxdbBaseDao.insert(url, dbName, insertList);
                    }
                } catch (Exception e) {
                    log.error(String.format("同步EAS设备报警记录异常: DeviceId:%s, DeviceName:%s", d.getDeviceId(), d.getDeviceName()), e);
                }
            } else {
                log.warn("EAS设备 【{}】 未设置 WebUrl", d.getDeviceId());
            }
        });
        log.info("------------------EAS设备报警记录同步完成------------------");
    }

    private Point buildPoint(long alertTime, String deviceId, String ecp, int rssi, int ruleNum) {
        return Point.measurement("eas_alarm")
                .time(alertTime * 1_000, TimeUnit.MILLISECONDS)
                .tag("device_id", deviceId)
                .addField("epc", ecp)
                .addField("rssi", rssi)
                .addField("rule_num", ruleNum)
                .build();
    }

}
